
package Server.ExtComponents.utilsKit.IDFactory;



import Server.ExtComponents.BaseConfig.config;
import org.apache.log4j.xml.DOMConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.BitSet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * This class ..
 * @version $Revision: 1.2 $ $Date: 2004/06/27 08:12:59 $
 */
public class BitSetIDFactory extends IdFactory{
    private static final Logger LOG = LoggerFactory.getLogger(BitSetIDFactory.class);
	private BitSet _freeIds;
	private AtomicInteger _freeIdCount;
	private AtomicInteger _nextFreeId;
    private static final  ExecutorService pool = Executors.newFixedThreadPool(3);

    /**
     * TEST
     * @param args
     */
    public static void main(String[]args){
        DOMConfigurator.configure(config.Game_log4j);
           for(int i=0;i<10;i++){
               LOG.info("获取的id：" + getIDFactory().getNextId());
           }
    }
    /**
     * 获取IDFACTORY
     * @return
     */
    public static IdFactory getIDFactory(){
        return singelton._instance;
    }

    private static final class singelton{
        protected static final IdFactory _instance=new BitSetIDFactory();
    }

    protected class BitSetCapacityCheck implements Runnable
	{
		@Override
		public void run()
		{
			synchronized (BitSetIDFactory.this)
			{
				if (reachingBitSetCapacity())
				{
					increaseBitSetCapacity();
				}
			}
		}
	}
	
	protected BitSetIDFactory()
	{
        super();
        synchronized (BitSetIDFactory.class){
            initialize();
            pool.execute(new BitSetCapacityCheck());

		}
        LOG.info(getClass().getSimpleName() + ": " + _freeIds.size() + " id's available.");
	}
	
	private void initialize(){
		try
		{
			_freeIds = new BitSet(PrimeFinder.nextPrime(0x5f606903));
			_freeIds.clear();
			_freeIdCount = new AtomicInteger(FREE_OBJECT_ID_SIZE);

			for (Integer usedObjectId :extractUsedObjectIDTable())
			{
				int objectID = usedObjectId - FIRST_OID;
				if (objectID < 0)
				{
                    LOG.warn(getClass().getSimpleName() + ": Object ID " + usedObjectId + " in DB is less than minimum ID of " + FIRST_OID);
					continue;
				}
				_freeIds.set(usedObjectId - FIRST_OID);
				_freeIdCount.decrementAndGet();
			}
			
			_nextFreeId = new AtomicInteger(_freeIds.nextClearBit(0));
			_initialized = true;
		}
		catch (Exception e)
		{
			_initialized = false;
            LOG.info(getClass().getSimpleName() + ": Could not be initialized properly: " + e.getMessage());
		}
	}
	
	@Override
	public synchronized void releaseId(int objectID)
	{
		if ((objectID - FIRST_OID) > -1)
		{
			_freeIds.clear(objectID - FIRST_OID);
			_freeIdCount.incrementAndGet();
		}
		else
		{
            LOG.warn(getClass().getSimpleName() + ": Release objectID " + objectID + " failed (< " + FIRST_OID + ")");
		}
	}
	
	@Override
	public synchronized int getNextId(){
		int newID = _nextFreeId.get();
		_freeIds.set(newID);
		_freeIdCount.decrementAndGet();
		
		int nextFree = _freeIds.nextClearBit(newID);
		
		if (nextFree < 0)
		{
			nextFree = _freeIds.nextClearBit(0);
		}
		if (nextFree < 0)
		{
			if (_freeIds.size() < FREE_OBJECT_ID_SIZE)
			{
				increaseBitSetCapacity();
			}
			else
			{
				throw new NullPointerException("Ran out of valid Id's.");
			}
		}
		
		_nextFreeId.set(nextFree);
		
		return newID + FIRST_OID;
	}
	
	@Override
	public synchronized int size()
	{
		return _freeIdCount.get();
	}
	
	/**
	 * @return
	 */
	protected synchronized int usedIdCount()
	{
		return (size() - FIRST_OID);
	}
	
	/**
	 * @return
	 */
	protected synchronized boolean reachingBitSetCapacity()
	{
		return PrimeFinder.nextPrime((usedIdCount() * 11) / 10) > _freeIds.size();
	}
	
	protected synchronized void increaseBitSetCapacity()
	{
		BitSet newBitSet = new BitSet(PrimeFinder.nextPrime((usedIdCount() * 11) / 10));
		newBitSet.or(_freeIds);
		_freeIds = newBitSet;
	}
}
